<template>
    <el-card class="user-info-card" shadow="hover">
        <div class="user-info-title">
            <h3>修改个人信息</h3>
        </div>
        <el-form :model="userForm" :rules="rules" label-width="100px" size="large">
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="userForm.realName" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="userForm.gender">
                    <el-radio value="男">男</el-radio>
                    <el-radio value="女">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="邮箱" prop="userEmail">
                <el-input v-model="userForm.userEmail" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="userPhone">
                <el-input v-model="userForm.userPhone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">保存</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup>
import userApi from "@/api/userApi";
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
const userForm = ref({
    realName: "",
    gender: "",
    userEmail: "",
    userPhone: ""
});
let userInfo = {};

// 获得用户信息
const getInfo = () => {
    let id = sessionStorage.getItem("userInfoUserId")
    userApi.getById(id)
        .then(resp => {
            if (resp.code === 10000) {
                userForm.value = resp.data;
                userInfo = resp.data;
            }
        });
}

const rules = {
    realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    gender: [{ required: true, message: "请选择性别", trigger: "change" }],
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    userEmail: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" }
    ],
    userPhone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        // { pattern: /^1[3456789]\d{9}$/, message: "请输入有效的手机号", trigger: "blur" }
    ]
};



const submitForm = () => {
    userApi.updateInfo(userForm.value)
        .then(resp => {
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
                getInfo();
            } else {
                ElMessage.error(resp.msg);
                // getInfo();
            }
        });
};

const resetForm = () => {
    console.log(userInfo);
    userForm.value = userInfo;
};

getInfo();
</script>

<style scoped>
.user-info-card {
    width: 500px;
    margin: 0 auto;
    padding: 20px;
}

.user-info-title {
    text-align: center;
    margin-bottom: 20px;
}
</style>